package com.example.dict.utils.Dictionary.Operations;

import com.example.dict.data.WordLoader;
import com.example.dict.utils.Dictionary.dictionaryOperations;
import com.example.dict.utils.util.LinkedList;
import com.example.dict.utils.util.Record;


/**
 * 哈希表实现
 * @author wey
 * */
public class Hash implements dictionaryOperations {

    /**
     * 全局字典
     * */
    static Hash dictionary;

    /**
     * 目录
     * */
    static LinkedList[] catalog = new LinkedList[26];

    /**
     * 初始化
     * */
    private Hash() {

    }


    /**
     * 获取字典
     *
     * @return 返回字典
     */
    public static Hash acquire() {
        if (dictionary == null) {
            dictionary = new Hash();

            for (char letter = 'a'; letter <= 'z'; letter++) {

                catalog[letter - 'a'] = new LinkedList();

                /* 文件路径 */
                String src = "dictionary_storage/" + letter + ".txt";

                /* 创建单词加载器 */
                WordLoader wordloader = new WordLoader(dictionary, src);

                /* 多线程、初始化字典 */
                wordloader.start();
            }
        }
        return dictionary;
    }


    /**
     * 翻译单词
     *
     * @param word 单词
     * @return 翻译
     */
    @Override
    public String translate(String word) {
        Record record = new Record();
        record = catalog[word.charAt(0) - 'a'].get(word);
        return (record == null) ? null : record.translation;
    }

    /**
     * 存储到字典里
     * @param word 单词
     * @param translation 翻译
     * */
    @Override
    public void insert(String word, String translation) {
        catalog[word.charAt(0) - 'a'].add(new Record(word, translation));
    }

    /**
     * 删除单词
     * @param word
     * */
    @Override
    public void delete(String word) {
        catalog[word.charAt(0) - 'a'].delete(word);
    }

    @Override
    public String translateC2E(String word){
        return null;
    }
}
